<template>
<div class="page-container">
    <div class="toolbar">
        <el-row>
            <el-tabs type="border-card">
                <el-tab-pane label="单据信息">
                    <el-form :inline="true" :model="operateDataForm" label-width="110px" style="text-align:left;" ref="operateDataForm" :disabled="isEdit" :rules="operateDataFormRules" class="form">
                        <el-row class="search-input">
                            <el-form-item label v-show="false">
                                <el-input v-model="operateDataForm.id" placeholder="请输入"></el-input>
                            </el-form-item>
                            <el-form-item label="仓库：" prop="storeObj">
                                <el-select v-model="operateDataForm.storeObj" placeholder="全部" @change="selectStore" value-key="id">
                                    <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item" @click="operateDataForm.deptName=item.name"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="单据类型：" prop="operateObj">
                                <el-select v-model="operateDataForm.operateObj" placeholder="全部" value-key="id" @change="changeOperate">
                                    <el-option v-for="item in operates" :key="item.id" :label="item.optionLabel" :value="item"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="单据编号：" prop="code">
                                <el-input v-model="operateDataForm.code" maxlength="10" max placeholder="请输入"></el-input>
                            </el-form-item>
                            <el-form-item label="批次：" prop="batchNo">
                                <el-input v-model="operateDataForm.batchNo" placeholder="请输入" oninput="value=value.replace(/^\.+|[^\d.]/g,'')"></el-input>
                            </el-form-item>
                            <el-form-item label="所属组织：" prop="deptId">
                                <el-select v-model="operateDataForm.deptId" disabled>
                                    <el-option v-for="item in deptList" :key="item.id" :label="item.deptName" :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="备注：">
                                <el-input type="textarea" v-model="operateDataForm.remark" maxlength="150" show-word-limit placeholder="请输入"></el-input>
                            </el-form-item>
                        </el-row>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </el-row>
        <el-row>
            <el-tabs type="border-card">
                <div class="tool-wrap">
                    <div class="search-button mt5" v-if="!isEdit">
                        <el-button-group>
                            <el-button type="primary" size="small" @click="addProduct">新增</el-button>
                            <el-button type="primary" size="small" @click="deleteProduct">删除</el-button>
                            <el-button type="primary" size="small" icon="el-icon-upload2" @click="importProduct">导入</el-button>
                            <el-button type="primary" size="small" icon="el-icon-download" @click="download">下载导入模板
                            </el-button>
                        </el-button-group>
                    </div>
                </div>
                <el-tab-pane label="  商品信息">
                    <el-table :data="tableData" height="250" border style="width: 100%" @selection-change="handleSelectionChange1">
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column prop="code" label="商品编码" width="180"></el-table-column>
                        <el-table-column prop="chineseName" label="商品名称" width="180"></el-table-column>
                        <el-table-column prop="artNo" label="货号"></el-table-column>
                        <el-table-column prop="barCode" label="商品条码"></el-table-column>
                        <el-table-column prop="unitName" label="主计量单位"></el-table-column>
                        <el-table-column v-if="isEdit" prop="applyNum" label="申请数量"></el-table-column>
                        <el-table-column v-if="isEdit" prop="actualNum" label="实际处理数量"></el-table-column>
                        <el-table-column prop="availableStock" label="可用库存"></el-table-column>
                        <el-table-column v-if="!isEdit" prop="applyNum" label="申请数量">
                            <template slot-scope="scope">
                                <div>
                                    <el-input @input="scope.row.applyNum=scope.row.applyNum.replace(/[^\d.]/g,'')" size="small" v-model="scope.row.applyNum" placeholder="请输入申请数量" @blur="changeNum(scope.row,scope.row.applyNum,scope.$index,1)"></el-input>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column v-if="!isEdit" prop="actualNum" label="实际处理数量">
                            <template slot-scope="scope">
                                <div>
                                    <el-input size="small" @input="scope.row.actualNum=scope.row.actualNum.replace(/[^\d.]/g,'')" v-model="scope.row.actualNum" placeholder="实际处理数量" @blur="changeNum(scope.row,scope.row.actualNum,scope.$index,2)"></el-input>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <div class="tool-wrap">
                    <div>
                        <el-button-group>
                            <el-button v-if="!isEdit" type="primary" size="small" @click="saveProduct(0)">保存</el-button>
                            <el-button v-if="outFlag" size="small" @click="saveProduct(1)" type="primary">出 库</el-button>
                            <el-button v-if="unOutFlag" size="small" @click="saveProduct(1)" type="primary">入 库</el-button>
                            <el-button type="primary" size="small" @click="back()">返回</el-button>
                        </el-button-group>
                    </div>
                </div>
            </el-tabs>
        </el-row>

        <!--新增商品弹窗-->
        <el-dialog title="选择商品" :visible.sync="dialogTableVisible" width="60%">
            <div class="search-wrap">
                <el-form :inline="true" :model="searchFilters" ref="searchFilters" label-position="right" label-width="200px">
                    <el-form-item label="商品">
                        <el-input v-model="searchFilters.chineseName" placeholder="请输入商品名称"></el-input>
                    </el-form-item>
                    <el-button size="mini" @click="queryProduct">查询</el-button>
                </el-form>
            </div>
            <div class="table-wrap">
                <el-table :data="tableProductData" height="500px" @selection-change="handleSelectionChange">
                    <el-table-column align="center" type="selection" width="55"></el-table-column>
                    <el-table-column align="center" prop="code" label="商品编码" width="180"></el-table-column>
                    <el-table-column align="center" prop="chineseName" label="商品名称" width="180"></el-table-column>
                    <el-table-column align="center" prop="artNo" label="货号"></el-table-column>
                    <el-table-column align="center" prop="barCode" label="商品条码"></el-table-column>
                    <el-table-column align="center" prop="name" label="主计量单位"></el-table-column>
                    <el-table-column align="center" prop="availableStock" label="可用库存"></el-table-column>
                </el-table>
                <!--分页栏-->
                <div class="toolbar" style="padding:10px;">
                    <el-pagination layout="total, prev, pager, next, jumper,sizes" @current-change="refreshPageRequest" @size-change="handleSizeChange" :current-page="pageRequest.pageNum" :page-size="pageRequest.pageSize" :total="totalSize" style="float:right;" :page-sizes="[10, 20, 30, 40]"></el-pagination>
                </div>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button @click="addOperateProduct">保 存</el-button>
                <el-button type="primary" @click="dialogTableVisible = false">取 消</el-button>
            </div>
        </el-dialog>

        <!--批量修改库存-->
        <el-dialog title="批量导入库内事物单" width="30%" height="30%" :visible.sync="showAddDialog" :close-on-click-modal="false" center>
            <div class="">
                <el-upload class="upload-demo" ref="upload" :on-exceed="handleExceed" :action="uploadExcel()" :on-success="handleSuccess" name="file" :before-upload="beforeUpload" :file-list="fileList" :auto-upload="false" :limit=1>
                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    <el-button size="small" type="success" @click="submitUpload">批量导入</el-button>
                </el-upload>
            </div>
        </el-dialog>
    </div>
</div>
</template>

<script>
export default {
    components: {},

    data() {
        return {
            fileList: [],
            isEdit: true,
            outFlag: false,
            unOutFlag: false,
            pageRequest: {
                pageNum: 1,
                pageSize: 10
            },
            totalSize: 0,
            limitUpload: 1,
            fileTemp: null,
            showAddDialog: false,
            selections: [],
            selectionsAdd: [],
            searchFilters: {
                chineseName: null,
                deptId: null,
            },
            dialogTableVisible: false,
            deptList: [],
            storeList: [],
            operates: [],
            tableData: [],
            tableProductData: [],
            operateDataForm: {
                id: null,
                type: 1,
                deptId: null,
                storeId: null,
                operateId: null,
                remark: null,
                batchNo: null,
                code: null,
                storeObj: null,
                operateObj: null,
            },
            operateDataFormRules: {
                storeObj: [{
                    required: true,
                    message: "请选择仓库",
                    trigger: "change"
                }],
                operateObj: [{
                    required: true,
                    message: "请选择单据类型",
                    trigger: "change"
                }],
                code: [{
                        required: true,
                        message: "请输入单据编号",
                        trigger: "change"
                    }, {
                        min: 2,
                        max: 8,
                        message: "长度在 2 到 8 个字符",
                        trigger: "blur"
                    },
                    {
                        pattern: /^[^\u4e00-\u9fa5]+$/,
                        message: '虚拟库编码不能包含汉字',
                        trigger: 'blur'
                    },
                    {
                        pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/,
                        message: '虚拟库编码不能包含特殊字符',
                        trigger: 'blur'
                    },
                ],
                batchNo: [{
                    required: true,
                    message: "请输入批次",
                    trigger: "change"
                }],

            },
        };
    },

    methods: {
        //申请数量和实际处理数量判断
        changeNum: function (row, num, index, type) {
            let this_ = this
            if (this_.outFlag) {
                if (Number(row.availableStock) < Number(num)) {
                    if (type == 1) {
                        this_.tableData[index].applyNum = null
                    } else {
                        this_.tableData[index].actualNum = null
                    }
                    this_.$message({
                        message: "出库数量不可大于当前库存",
                        type: "info"
                    });
                }
            }
        },
        //操作类型选择
        changeOperate: function (item) {
            if (item.type == 1) {
                this.unOutFlag = true
                this.outFlag = false
            } else if (item.type == 2) {
                this.outFlag = true
                this.unOutFlag = false
            }
        },
        //初始化所属组织
        getDeptList: function () {
            let this_ = this;
            this.utils.request.queryDeptList({}, function (res) {
                if (res.code == "0000") {
                    this_.deptList = res.data;
                }
            });
        },
        //2.请求列表数据
        getDetail() {
            let this_ = this
            let params = {};
            params.id = this.$route.params.id;
            this.utils.request.getMStoreOperateDetail(params, function (res) {
                if (res.code === "0000") {
                    let storeObj = new Object();
                    storeObj.id = res.data.storeId.toString()
                    let operateObj = new Object()
                    operateObj.id = res.data.operateId
                    this_.operateDataForm = {
                        id: res.data.id,
                        deptId: res.data.deptId,
                        storeId: res.data.storeId,
                        operateId: res.data.operateId,
                        remark: res.data.remark,
                        batchNo: res.data.batchNo,
                        code: res.data.code,
                        storeObj: storeObj,
                        operateObj: operateObj,
                        type: 1
                    }
                    if (!this_.isEdit) {
                        let obj = new Object()
                        obj.type = res.data.operateType
                        this_.changeOperate(obj)
                    }
                } else {
                    this_.$message({
                        message: "操作失败, " + res.msg,
                        type: "error"
                    });
                }
            });
            //加载详细记录列表
            this.utils.request.getMStoreOperateProductsDetail({
                operateId: this.$route.params.id
            }, function (res) {
                if (res.code === "0000") {
                    this_.tableData = res.data;
                } else {
                    this_.$message({
                        message: "操作失败, " + res.msg,
                        type: "error"
                    });
                }
            })
        },
        //返回上一页;
        back() {
            this.$router.push({
                path: "/Pages/Store/MStoreOperateList"
            });
        },
        //仓库初始化
        getStore() {
            let this_ = this;
            this.utils.request.getMStoreList({}, function (res) {
                if (res.code === "0000") {
                    this_.storeList = res.data;
                } else {
                    this_.$message({
                        message: "操作失败, " + res.msg,
                        type: "error"
                    });
                }
            });
        },
        //仓库选择
        selectStore(item) {
            this.operateDataForm.deptId = item.deptId
        },
        //单据类型初始化
        getOperate() {
            let this_ = this;
            this.utils.request.getOperateList({}, function (res) {
                if (res.code === "0000") {
                    this_.operates = res.data;
                } else {
                    this_.$message({
                        message: "操作失败, " + res.msg,
                        type: "error"
                    });
                }
            });
        },
        //打开弹框
        addProduct() {
            let this_ = this;
            if (this_.operateDataForm.storeObj == null) {
                this_.$message({
                    message: "请选择仓库",
                    type: "info"
                });
            } else {
                this.dialogTableVisible = true;
                this.queryProduct();
            }
        },
        //查询商品
        queryProduct(params) {
            let this_ = this;
            if (params == undefined || params == null) {
                params = {
                    pageNum: this_.pageRequest.pageNum,
                    pageSize: this_.pageRequest.pageSize
                };
            }
            if (this_.searchFilters == undefined || this_.searchFilters == null) {
                this_.searchFilters = {};
            }
            this_.searchFilters.start = params.pageNum;
            this_.searchFilters.limit = params.pageSize;
            this_.searchFilters.deptId = this_.operateDataForm.deptId
            this.utils.request.queryShopInventory(this_.searchFilters, function (res) {
                this_.tableProductData = res.data.rows;
                this_.totalSize = Number(res.data.total);
            });
        },
        //删除商品
        deleteProduct() {
            this.selectionsAdd.forEach(item => {
                this.tableData.forEach((item1, index) => {
                    if (item.productId == item1.productId) {
                        this.tableData.splice(index, 1);
                    }
                });
            });
        },
        //导入商品
        importProduct() {
            if (this.operateDataForm.storeObj == null) {
                this.$message({
                    message: "请选择仓库",
                    type: "info"
                });
                return;
            } else {
                this.showAddDialog = true;
                this.fileList = []
            }

        },
        //添加商品
        addOperateProduct() {
            let this_ = this;
            if (this_.selections.length == 0) {
                this_.$message({
                    message: "请选择商品",
                    type: "info"
                });
            } else {
                this_.dialogTableVisible = false;
                this_.$message({
                    message: "操作成功",
                    type: "success"
                });
                if (this_.tableData.length == 0) {
                    this_.selections.forEach(item => {
                        let obj = {}
                        obj.code = item.code
                        obj.chineseName = item.chineseName
                        obj.artNo = item.artNo
                        obj.productId = item.productId
                        obj.barCode = item.barCode
                        obj.availableStock = item.availableStock
                        obj.unitName = item.name
                        obj.applyNum = null
                        obj.actualNum = null
                        this_.tableData.push(obj)
                    })
                } else {
                    this_.tableData.forEach(item => {
                        this_.selections.forEach(function (item1, index) {
                            if (item.productId == item1.productId) {
                                this_.selections.splice(index, 1)
                            } else {
                                let obj = {}
                                obj.code = item1.code
                                obj.chineseName = item1.chineseName
                                obj.productId = item1.productId
                                obj.artNo = item1.artNo
                                obj.barCode = item1.barCode
                                obj.availableStock = item1.availableStock
                                obj.unitName = item1.name
                                obj.applyNum = null
                                obj.actualNum = null
                                this_.tableData.push(obj)
                            }
                        })
                    })
                }
            }
        },
        // 每页数据刷新
        refreshPageRequest: function (pageNum) {
            this.pageRequest.pageNum = pageNum;
            this.queryProduct(this.pageRequest1);
        },
        // 每页条数刷新
        handleSizeChange: function (pageSize) {
            this.pageRequest.pageSize = pageSize;
            this.queryProduct();
        },
        //出库、入库、保存
        saveProduct(param) {
            let this_ = this;
            this.$refs["operateDataForm"].validate(valid => {
                if (valid) {
                    let flag = false
                    if (this_.tableData.length == 0) {
                        this_.$message({
                            message: "请选择商品",
                            type: "info"
                        });
                        flag = true
                    } else {
                        this_.tableData.forEach(function (item, index) {
                            if (item.applyNum == null || item.applyNum == "") {
                                let rowIndex = index + 1
                                this_.$message({
                                    message: "第 " + rowIndex + " 行商品信息申请数量不能为空",
                                    type: "info"
                                });
                                flag = true
                                return;
                            }
                            if (item.actualNum == null) {
                                let rowIndex = index + 1
                                this_.$message({
                                    message: "第 " + rowIndex + " 行商品信息实际处理数量不能为空",
                                    type: "info"
                                });
                                flag = true
                                return;
                            }
                        })
                    }
                    if (!flag) {
                        this.$confirm("确认提交吗？", "提示", {}).then(() => {
                            let params = Object.assign({}, this.operateDataForm);
                            params.products = this.tableData
                            params.storeId = this.operateDataForm.storeObj.id
                            params.operateId = this.operateDataForm.operateObj.id
                            params.status = param
                            this.utils.request.saveOrUpdateMStoreOperate(params, function (res) {
                                if (res.code == "0000") {
                                    this_.$message({
                                        message: "操作成功",
                                        type: "success"
                                    });
                                    this_.$router.push({
                                        path: "/Pages/Store/MStoreOperateList"
                                    });
                                } else {
                                    this_.$message({
                                        message: "操作失败," + res.msg,
                                        type: "error"
                                    });
                                }
                            });
                        });
                    }
                }
            });
        },
        //导入
        uploadExcel() {
            return "http://localhost:8087/jic-product/productExcel/mStoreOperateDetailExcel" +
                "?deptId=" + this.operateDataForm.deptId;
        },
        //导入之后方法
        handleSuccess: function (res) {
            let this_ = this
            if (res.code == "0000") {
                this_.showAddDialog = false;
                this_.$message({
                    message: "操作成功",
                    type: "success"
                });
                if (res.data.length > 0 && this_.tableData.length > 0) {
                    this_.tableData.forEach(item => {
                        res.data.forEach(function (item1, index) {
                            if (item.productId == item1.productId) {
                                this_.tableData.splice(index, 1)
                                let obj = {}
                                obj.code = item1.code
                                obj.chineseName = item1.chineseName
                                obj.productId = item1.productId
                                obj.artNo = item1.artNo
                                obj.barCode = item1.barCode
                                obj.availableStock = item1.availableStock
                                obj.unitName = item1.unitName
                                obj.applyNum = item1.applyNum
                                obj.actualNum = item1.actualNum
                                this_.tableData.push(obj)
                            } else {
                                let obj = {}
                                obj.code = item.code
                                obj.chineseName = item.chineseName
                                obj.productId = item.productId
                                obj.artNo = item.artNo
                                obj.barCode = item.barCode
                                obj.availableStock = item.availableStock
                                obj.unitName = item.unitName
                                obj.applyNum = item.applyNum
                                obj.actualNum = item.actualNum
                                this_.tableData.push(obj)
                            }
                        })
                    })
                } else {
                    res.data.forEach(function (item, index) {
                        let obj = {}
                        obj.code = item.code
                        obj.chineseName = item.chineseName
                        obj.productId = item.productId
                        obj.artNo = item.artNo
                        obj.barCode = item.barCode
                        obj.availableStock = item.availableStock
                        obj.unitName = item.unitName
                        obj.applyNum = item.applyNum
                        obj.actualNum = item.actualNum
                        this_.tableData.push(obj)
                    })
                }
            } else {
                this.$message({
                    message: "操作失败, " + res.msg,
                    type: "error"
                });
            }
        },
        //上传之前校验格式
        beforeUpload(file) {
            const isExcel =
                file.type === 'application/vnd.ms-excel' ||
                file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            if (!isExcel) {
                this.$message.error('上传文件只能是.xls,.xlsx格式!')
                return isExcel
            }
        },

        //提交模板
        submitUpload() {
            this.$refs.upload.submit();
        },
        //超出最大上传文件数量时的处理方法
        handleExceed() {
            this.$message({
                type: "warning",
                message: "超出最大上传文件数量的限制！"
            });
            return;
        },
        //移除文件的操作方法
        handleRemove(file, fileList) {
            this.fileTemp = null;
        },
        //下载导入模板
        download() {
            var $form = $('<form method="GET"></form>');
            $form.attr("action", "/static/oPeratetemplete.xlsx");
            $form.appendTo($("body"));
            $form.submit();
        },
        handleSelectionChange(val) {
            this.selections = val;
        },
        handleSelectionChange1(val) {
            this.selectionsAdd = val;
        }
    },

    mounted() {
        this.getDeptList()
        this.getStore();
        this.getOperate();
        if (this.$route.params.type == 2) {
            this.isEdit = true
            this.getDetail()
        } else if (this.$route.params.type == 1) {
            this.isEdit = false
            this.getDetail()
        } else {
            this.isEdit = false
        }
    }
};
</script>

<style lang="scss" scoped>
/* ele组件样式重置 */
.common-content {
    padding: 10px;
    box-sizing: border-box;

    .search-wrap /deep/ {
        .el-form-item__label {
            height: 32px;
            line-height: 32px;
        }

        .el-form-item__content {
            height: 32px;
            line-height: 32px;
            width: 150px;
        }

        .el-input--mini .el-input__inner {
            height: 32px;
            line-height: 32px;
        }

        .el-date-editor.el-input,
        .el-date-editor.el-input__inner {
            width: 150px;
        }
    }

    /* 多日期样式重置 */
    .el-dater /deep/ .el-form-item__content {
        width: 330px;
    }

    /* 通用工具部分样式 */
    .tool-wrap {
        width: 100%;
        height: auto;
        position: relative;
        overflow: hidden;

        .left-area {
            float: left;
            width: 50%;
            text-align: left;

            button {
                margin-right: 15px;
                border-radius: 5px;
            }
        }

        .right-area {
            float: right;
            width: 50%;
            text-align: right;
        }
    }

    /* 表格部分样式 */
    .table-wrap {
        width: 100%;
        max-height: 600px;
        margin-top: 20px;
    }

    /* 弹窗样式 */
    .dialog-wrap /deep/ .el-dialog__footer {
        text-align: center !important;
    }
}

.search-input {
    padding-top: 20px;
    padding-bottom: 0px;
}

.mt5 {
    margin-top: 5px;
}
</style>
